<template>
	<view class="parent container">
		<view class="card">
			<view class="tip">昵称</view>
			<uni-easyinput placeholder="请填写昵称" trim="all" v-model="business.shop_name" />
		</view>
		<view class="card">
			<view class="tip">商品起送价</view>
			<uni-easyinput placeholder="请填写商品起送价" @input="num($event)" type="digit" v-model="business.min_price" />
		</view>

		<view class="card">
			<view class="tip">地址</view>
			<view class="card-address" @click.stop="getAddress">
				<uni-easyinput placeholder="请选择地址" diabled trim="all" v-model="business.address" />
			</view>
		</view>
		<view class="card">
			<view class="tip">某宝姓名</view>
			<uni-easyinput placeholder="请输入某宝姓名(用来提现)" trim="all" v-model="business.ali_name" maxlength="11" />
		</view>

		<view class="card">
			<view class="tip">某宝手机号</view>
			<uni-easyinput placeholder="请输入某宝手机号(用来提现)" trim="all" v-model="business.ali_phone" maxlength="11" />
		</view>
		<view class="card">
			<view class="tip">验证码</view>
			<view class="row">
				<uni-easyinput placeholder="请填写验证码" maxlength="8" trim="all" v-model="business.code" />
				<view @click="getSms" class="code" :style="{ background: time != outTime ? '#d1c8cd' : ' #a5d63f' }">{{ codeStr }}</view>
			</view>
		</view>
		<view class="card">
			<view class="tip">提现费率</view>
			<uni-easyinput disabled :value="sysState.fee_rate" maxlength="11" />
		</view>
		<view class="submit btn" @click="submit">提交</view>
	</view>
</template>

<script setup lang="ts">
import { ref, nextTick, onUnmounted } from 'vue';
import { Rules } from 'async-validator';
import Schema from 'async-validator';
import { onShow } from '@dcloudio/uni-app';
import { state as userState } from '../../store/user';
import { state as shopState } from '../../store/shop';
import { state as sysState } from '../../store/system';
import { state as globalState, setAddress, setLongitude, setLatitude } from '../../store/global';
import getShop from '../../vendor/shop/shop';
import getUser from '../../vendor/user';
import http from '../../vendor/http';
const { getCode, validateCode } = getUser();

const profile: Rules = {
	shop_name: {
		type: 'string',
		required: true,
		message: '请填写昵称'
	},
	min_price: {
		type: 'number',
		required: true,
		message: '请填写商品起送价'
	},
	ali_name: {
		type: 'string',
		required: true,
		message: '请填写某宝提现姓名'
	},
	ali_phone: {
		type: 'string',
		required: true,
		message: '请填写某宝提现手机号',
		asyncValidator: (rule, value) => {
			return new Promise<void>((resolve, reject) => {
				const r = /^1[3-9]\d{9}$/.test(value);
				if (!r) {
					reject('请验证某宝手机号正确性'); // reject with error message
				} else {
					resolve();
				}
			});
		}
	},
	address: {
		type: 'string',
		required: true,
		message: '请选择地址'
	},
	code: {
		type: 'string',
		required: true,
		message: '请填写验证码'
	}
};

const { getMiniCode } = getShop();

const business = ref({
	shop_name: userState.nickname,
	min_price: userState.store_mini_price,
	mobile: userState.store_phone,
	ali_name: userState.ali_name,
	ali_phone: userState.ali_phone,

	longitude: userState.store_longitude, // 经度
	latitude: userState.store_latitude, // 维度
	address: userState.store_address, // 经营地址
	code: ''
});

const getAddress = () => {
	uni.navigateTo({
		url: '/pages/map'
	});
};
const num = (e: string, index: number) => {
	e = e.match(/^\d*(\.?\d{0,2})/g)[0] || null;
	nextTick(() => {
		business.value.min_price = parseFloat(e);
	});
};

onShow(() => {
	business.value.address = globalState.address ? globalState.address : userState.store_address;
	business.value.longitude = globalState.longitude ? globalState.longitude : userState.store_longitude;
	business.value.latitude = globalState.latitude ? globalState.latitude : userState.store_latitude;
});

onUnmounted(() => {
	// 重置地址
	setAddress('');
	setLongitude('');
	setLatitude('');
});

const submit = () => {
	const validator = new Schema(profile);

	validator
		.validate(business.value)
		.then(() => {
			// 验证验证码
			validateCode(business.value.ali_phone, business.value.code, (res: any) => {
				switch (res.status) {
					case 2:
					case 3:
						toasting(res.msg);
						break;
					case 1:
						uni.showLoading();

						// 获取小程序码
						if (!userState.store_mini_code) {
							getMiniCode((res: any) => {
								const fs = wx.getFileSystemManager();
								const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_image.png`;
								if(res.msg == "失败"){
									toasting('保存失败,请稍后重试~');
									uni.hideLoading();
								}

								// 将 Base64 数据写入临时文件
								var imageData = res.url.replace(/^data:image\/\w+;base64,/, '');
								const fileName = new Date().getMilliseconds() + '.jpg';
								fs.writeFileSync(tempFilePath, imageData, 'base64');
								uniCloud.uploadFile({
									filePath: tempFilePath,
									cloudPath: fileName, // 云存储中的路径
									success: (res) => {
										fs.unlinkSync(tempFilePath);
										userState.store_mini_code = res.fileID;
										save();
									},
									fail: (err) => {
										console.error('上传失败:', err);
										toasting('保存失败,请稍后重试~');
										uni.hideLoading();
									}
								});
							});
						} else {
							save();
						}

						break;
				}
			});
		})
		.catch(({ errors }) => {
			toasting(errors[0].message);
		});
};

const save = () => {
	const params = {
		nickname: business.value.shop_name,
		phone: business.value.ali_phone, //  简单性  支付宝手机号=联系人手机号
		longitude: business.value.longitude,
		latitude: business.value.latitude,
		address: business.value.address,
		avatar: userState.avatar,
		location: userState.store_location,

		ali_name: business.value.ali_name,
		ali_phone: business.value.ali_phone,
		min_price: business.value.min_price * 100, // 参数是分
		mini_code: userState.store_mini_code
	};
	uni.showLoading()

	http.fetchPatch('/mer_profile', params).then((res: any) => {
		if (res.msg == '成功') {
			userState.nickname = business.value.shop_name;
			userState.store_phone = business.value.ali_phone;
			userState.store_longitude = business.value.longitude;
			userState.store_latitude = business.value.latitude;
			userState.store_address = business.value.address;
			userState.ali_name = business.value.ali_name;
			userState.ali_phone = business.value.ali_phone;

			userState.store_mini_price = business.value.min_price;

			toasting('保存成功~');
			setTimeout(() => {
				uni.navigateBack();
			}, 1800);
		} else {
			toasting('保存失败,请稍后重试~');
		}
		
		uni.hideLoading()
		
	});
};

let time = ref(120);
const outTime = ref(120);

const codeStr = ref('获取验证码');
const getSms = () => {
	if (time.value != outTime.value) return;

	const testPhone = /^1[3-9]\d{9}$/.test(business.value.ali_phone);

	if (!business.value.ali_phone || !testPhone) {
		toasting('请填写手机号');
		return;
	}

	//发送验证码
	getCode(business.value.ali_phone, () => {
		toasting('验证码已发送成功~');

		const t = setInterval(() => {
			time.value -= 1;
			codeStr.value = `${time.value}s后获取`;
		}, 1000);

		setTimeout(() => {
			time.value = outTime.value;
			clearInterval(t);
			codeStr.value = '获取验证码';
		}, outTime.value * 1000);
	});
};

const toasting = (title: string, icon: any = 'none') => {
	uni.showToast({
		title,
		icon
	});
};
</script>

<style scoped lang="scss">
.top {
	.icon {
		width: 26px;
	}
	.title {
		font-size: 20px;
	}
}
.row {
	display: flex;
}
.card {
	margin-top: $uni-spacing-row-base;
	.tip {
		font-size: $uni-font-size-lg;
		margin-bottom: 5px;
	}
}
:deep .file-picker__box {
	width: 100% !important;
	height: 125px !important;
}
.upload {
	text-align: center;
	width: 200px;
	height: 120px;
	margin-right: 5px;
	color: $uni-color-paragraph;
	font-size: $uni-font-size-base;
	position: relative;
	.img-tip {
		pointer-events: none;
		text-align: center;
		position: absolute; /* 绝对定位 */
		top: 50%; /* 距离父容器顶部的距离为50% */
		left: 50%; /* 距离父容器左侧的距离为50% */
		transform: translate(-50%, -50%); /* 通过平移来实现垂直居中 */
	}
}
.img-icon {
	width: 100px;
}
.upload-imgs {
	.img-tip {
		text-align: center;
	}
	display: flex;
	justify-content: space-between;
}
.num {
	margin-bottom: $uni-spacing-row-base;
}
.btn {
	text-align: center;
	color: white;
	line-height: 50px;
	width: 180px;
	border-radius: $uni-border-radius-lg;
	background: #a5d63f;
	margin: 80px auto;
}

.parent {
	padding: 0 15px;
}
.row {
	display: flex;
	.code {
		color: white;
		padding: 0 3px;
		margin-left: 5px;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
}
.space {
	height: 5px;
}
:deep .is-disabled {
	background: white !important;
	color: black;
}
</style>
